const { existsSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } = require('fs')
const { resolve } = require('path')

const templateReg = /\<template\>(.*?)\<\/template\>/
const scriptReg = /\<script\>(.*?)\<\/script\>/
const styleReg = /\<style\>(.*?)\<\/style\>/

function getTagContent(source, tagName) {
  const _reg = new RegExp(`<${tagName}>(.*?)</${tagName}>`, 'i')
  const _str = source.match(_reg)[1]
  return _str
}

function vueLoader(source) {

  const _str = source.replace(/[\r\n]/g, '')
  const template = getTagContent(_str, 'template')
  const script = getTagContent(_str, 'script')
  const style = getTagContent(_str, 'style')
  const cssFileName = `__temp/css/__${new Date().getTime()}.css`

  writeFile(cssFileName, style)
  const vueScript = script.replace(/\{(.*?)/, (node, key) => {
    return `
      { template: '${template}',
    `
  })


  return `
    import '../${cssFileName}'
    ${vueScript}
  `
}

/** 创建文件，并写入内容 */
function writeFile(fileName, content) {
  if (!existsSync(formatPath('../../__temp'))) {
    mkdirSync(formatPath('../../__temp'))
    mkdirSync(formatPath('../../__temp/css/'))
  }

  /** 读取是否存在遗留文件，并做删除操作 */
  const files = readdirSync(formatPath('../../__temp/css/'))
  files && files.forEach(file => {
    unlinkSync(formatPath('../../__temp/css/' + file))
  })

  writeFileSync(formatPath(`../../${fileName}`), content)
}

/** 格式化标准路径(以当前文件作为参考) */
function formatPath(path) {
  return resolve(__dirname, path)
}

module.exports = vueLoader